// pages/member-recommendCode/member-recommendCode.js
import api from '../../utils/api.js'
let app = getApp();
import QR from '../../utils/qrcode.js'
import {
    HTTP
} from '../../utils/http.js';
import { config } from '../../utils/config'
let http = new HTTP();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        share: false, // 页面进入方式：是否由分享进入
        percent: 0,
        showModel: false,
        nickName: '',
        downloadUrl: '',
        imgUrl: config.imgUrl,
    },
    //web-view下载
    goDownLoad(e) {
        wx.navigateTo({
            url: "/pages/downLoadApp/downLoadApp",
        })
    },
    getAppQrCode() {
        http.request({
            url: "/app_apply/get_version",
            success: (res) => {
                console.log('1111111111', res);
                if (res.code == 200) {
                    let downloadUrl = res.data.download;
                    this.createQrCode(`${downloadUrl}`, 'mycanvas', 185, 185)
                    this.setData({
                        downloadUrl
                    })
                }
            }
        })

    },
    onLoad: function (options) {
        this.getAppQrCode()
        console.log('options', options)
        if (options.user_id) {
            //比如 商家由微信好友分享 进入推荐码页面，点击下载app
            // 分享的页面应是 推荐人的 推荐码，而不是商家的
            this.setData({
                invite_code: options.invite_code,
                nickName: options.nickName,
                share: true
            })
        } else {
            let nickName = wx.getStorageSync('nickName');
            this.sureInviteCode(78)
            this.setData({
                nickName
            })
        }
    },
    //判断用户是否已有邀请码
    sureInviteCode(id) {
        http.request({
            url: api.sureInviteCode,
            data: {
                id: id
            },
            success: (res) => {
                if (res.data == 1) {
                    //该用户已有推荐码
                    let msg = res.message
                    this.getInviteCode(id);
                } else {
                    //该用户还没有相关推荐码
                    this.getNewUserInviteCode(id)
                }
            }
        })
    },
    //新版本生成用户唯一邀请码
    getNewUserInviteCode(id) {
        http.request({
            url: api.getNewUserInviteCode,
            data: {
                id: id
            },
            success: (res) => {
                console.log('创建成功', res)

                this.getInviteCode(id);
            }
        })
    },
    //已有，获取邀请码
    getInviteCode(id) {
        http.request({
            url: api.getInviteCode,
            data: {
                id: id
            },
            success: (res) => {
                console.log('我的推荐码', res)

                this.setData({
                    invite_code: res.invite_code
                })
            }
        })
    },
    copyText: function (e) {
        let invite_code = this.data.invite_code;
        console.log(e)
        wx.setClipboardData({
            data: invite_code,
            success: function (res) {
                wx.getClipboardData({
                    success: function (res) {
                        console.log(res)
                        wx.showToast({
                            title: '复制成功'
                        })
                    }
                })
            }
        })
    },
    downloadAPK() {
        let self = this;
        let showModel = this.data.showModel;
        if (showModel == false) {
            this.setData({
                showModel: true,
                showProgress: true
            })

        }

        self.downloadTask = wx.downloadFile({
            url: 'https://api.weigeee.com/app.apk',
            success: (res) => {
                console.log(res)
                wx.saveFile({
                    tempFilePath: res.tempFilePath,
                    success: function (res) {
                        console.log('保存成功了！')
                    },
                    fail: function (res) {
                        console.log(res)
                    },
                    complete: function (res) {
                        console.log('complete后的res数据：', res)
                    }
                })

            },
            fail: function (errMsg) {
                console.log('downloadFile fail, err is:', errMsg)
            },
            complete: function () {
                // self.downloadTask = null
                self.setData({
                    showModel: false,
                    showProgress: false
                })
            }
        })

        self.downloadTask.onProgressUpdate((res) => {
            console.log('下载进度', res.progress)
            this.setData({
                percent: res.progress
            })
            if (res.progress == 100) {
                wx.showToast({
                    title: '下载成功',
                })
                this.setData({
                    showModel: false,
                    showProgress: false
                })
            }
        })


    },
    cancelAPK() {
        let self = this;
        self.downloadTask.abort()
    },
    //获取相册授权,保存二维码
    saveImg() {
        // wx.getSetting({
        //   success(res) {
        //     if (!res.authSetting['scope.writePhotosAlbum']) {
        //       wx.authorize({
        //         scope: 'scope.writePhotosAlbum',
        //         success() {
        //           console.log('授权成功')
        //         }
        //       })
        //     }
        //   }
        // })
        var that = this;
        wx.getImageInfo({ //将获取图片的信息
            src: '{{imgUrl}}/images/member/wg_apk.png', // 需要下载的图片
            success(res) {
                var filePath = res.path //得到本地的路径
                wx.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success(res) {
                        console.log(res)
                        wx.showToast({
                            title: '保存成功',
                            icon: 'success'
                        })
                    }
                })
            }
        })
    },

    //生成二维码
    createQrCode: function (content, canvasId, cavW, cavH) {
        //调用插件中的draw方法，绘制二维码图片
        QR.api.draw(content, canvasId, cavW, cavH);
        this.canvasToTempImage(canvasId);
    },

    //获取临时缓存图片路径，存入data中
    canvasToTempImage: function (canvasId) {
        let that = this;
        wx.canvasToTempFilePath({
            canvasId, // 这里canvasId即之前创建的canvas-id
            success: function (res) {
                let tempFilePath = res.tempFilePath;
                console.log(tempFilePath);
                that.setData({ // 如果采用mpvue,即 this.imagePath = tempFilePath
                    imagePath: tempFilePath,
                });
            },
            fail: function (res) {
                console.log(res);
            }
        });
    },
    onShareAppMessage(res) {
        console.log('ppp', res)
        let user_id = wx.getStorageSync("user_id");
        let nickName = this.data.nickName;
        let invite_code = this.data.invite_code;
        if (res.from === 'button') { //button  menu
            console.log(1111111111)
            // 来自页面内转发按钮
            var content = {
                title: 'APP下载',
                path: `/pages/member-recommendCode/member-recommendCode?invite_code=${invite_code}&user_id=${user_id}&nickName=${nickName}`,
                success: function (res) {
                    console.log('成功', res)
                }
            }
        }
        return content
    },
})